<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Session;
use App\Services\UserService;

class UserController extends Controller{
	public function list(Request $request){

		$username = Session::get('username');

		if(!$username){
			return redirect('/admin/login'); 	
		}else{
			$data['page_size_list'] = array(20,25,50,100);
			$data['page_size'] = $request->input('page_size') ? intval($request->input('page_size')) : 3;
			$data['keywords'] = $request->input('username') ? addslashes($request->input('username')) : '';

			$user = new UserService;
			$data['username'] = $username;
			$data['userlist'] = $user->getUserList($data['page_size'],$data['keywords']);
		}

		return view('admin.user.list',$data);
	}

	public function create(){
		$username = Session::get('username');

		if(!$username){
			return redirect('/admin/login');
		}else{
			$data['username'] = $username;
		}

		return view('admin.user.add',$data);
	}

	public function store(){
		$user = new UserService;
		date_default_timezone_set('PRC');

		$data['username'] = addslashes($_POST['username']);
		$data['token'] = substr(md5(addslashes($_POST['password'])),0,8);
		$data['password'] = md5($data['token'].$_POST['password']);
		$data['name'] = addslashes($_POST['name']);
		$data['check'] = 'normal';
		$data['add_date'] = date('Y-m-d H:i:s');

		$info = $user->getUserInfoByName('username',$data['username']);
		if(!empty($info)){
			$_data = array('code'=>300);
		}else{
			$res = $user->insertUser($data);
			if($res){
				$_data = array('code'=>200);
			}else{
				$_data = array('code'=>400);
			}
		}

		return response()->json($_data);
	}

	public function edit($id){
		$username = Session::get('username');

		if(!$username){
			return redirect('/admin/login');
		}else{
			$user = new UserService;
			$data['username'] = $username;
			$data['info'] = $user->getUserInfoById($id);
		}

		return view('admin.user.edit',$data);
	}

	public function update(){
		$user = new UserService;
		$id = intval($_POST['userid']);
		$data['token'] = substr(md5(addslashes($_POST['password'])),0,8);
		$data['password'] = md5($data['token'].$_POST['password']);
		$res = $user->modifyUser($id,$data);
		if($res){
			$_data = array('code'=>200);
		}else{
			$_data = array('code'=>400);
		}

		return response()->json($_data);
	}

	public function del($id){
		$user = new UserService;
		$data['check'] = 'disable';
		$res = $user->modifyUser($id,$data);
		if($res){
			$_data = array('code'=>200);
		}else{
			$_data = array('code'=>400);
		}

		return response()->json($_data);
	}
}